<?php
/**
* object-oriented file system manipulation as nodes.
* This file belongs to a webappkit package (kit)
* @link http://webappkit.net
* @package pathnodes
* @subpackage common
* @author J.Ducastel <jeremie@ducastel.name>
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

/**
* registers as low-level pathnode subclass
*/
pathnode::heritage('foldernode',2);
/**
* generic folder node
*/
class folderNode extends pathNode {

	/**
	* detects if path applies to self class
	* @param string $path
	* @access public
	* @return bool
	*/
	function selfDetector($path) {
		return is_dir($path);
	}/**/

	/**
	* execute regular expression search on children nodes names and returns matches
	* @param string $regex
	* @todo recursion
	* @access public
	* @return array of pathNode derived instances
	*/
	function regexSearchName($regex,$recursive=false) {
		if (!$children=$this->getChildren()) {
			//trigger_error("foldernode->regexSearchName($regex) : folder {$this->path} has no children");
			return false;
		}
		//echo count($children);
		$matches=array();
		for ($f=0; $f<count($children); $f++) {
			if (is_a($children[$f],'foldernode')) {
				if (!$recursive)
					continue;
				$childMatches=$children[$f]->regexSearchName($regex,$recursive);
				$matches=array_merge($matches,$childMatches);
			}
			//$child=&$children[$f];
			$basename=$children[$f]->getbasename();
			if (ereg($regex,$basename))
				$matches[]=&$children[$f];
			// else echo "<p>$basename doesn't match $regex</p>";
		}
		return $matches;
	}/**/

	/**
	* sets node children if necessary and returns them
	* @access public
	* @return array of pathNode derived instances
	*/
	function & getChildren() {
		$false=false;
		if (!$this->exists()) return $false;
		if (!$this->children) {
			$d=dir($this->getAbsolutePath());
			while ($path=$d->read()) {
				// avoiding path starting by .
				if (substr($path,0,1)=='.') continue;
				$node=&pathNode::getNode($this->getAbsolutePath().'/'.$path);
				//$node->setParent($this);
				$this->children[]=&$node;
			}
		}
		return $this->children;
	}/**/

	/**
	* returns a child element as a pathnode instance
	* @access public
	* @param string $path filename
	* @return pathNode
	*/
	function & getChild($path) {
		if (!isset($this->children[$path])) {
			$this->children[$path]=&pathnode::getNode($this->absolute_path.'/'.$path);
		}
		return $this->children[$path];
	}/**/

	/**
	* return flat array of descendants.
	* = children, grandchildren etc
	* @access public
	* @return array
	*/
	function & getDescendants() {
		return $this->regexSearchName('.*',true);
	}/**/

	/**
	* creates dir if not exists
	* @param int $mode
	* @access public
	* @return bool
	*/
	function create($mode=0777) {
		return mkdir($this->path,$mode);
	}/**/
	/**
	* @var array children nodes
	*/
	var $children;

}
?>